﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Zero.Common
{
    /// <summary>
    /// Helper for locating transport objects through reflection.
    /// </summary>
    /// <seealso cref="IRequest{TResponse}"/>
    public static class TransportTypesLocator
    {
        /// <summary>
        /// Returns range of types, that are used as transport objects.
        /// </summary>
        /// <returns></returns>
        public static IEnumerable<Type> GetTransportTypes()
        {
            var assemblies = AppDomain.CurrentDomain.GetAssemblies();

            var transportTypes =
                assemblies.SelectMany(x => x.GetTypes()).SelectMany(GetRelatedTransportTypes).Where(x => x != null).
                    Distinct().ToList();

            return transportTypes;
        }

        private static IEnumerable<Type> GetRelatedTransportTypes(Type type)
        {
            Type impementsIRequest =
                type.GetInterfaces()
                    .Where(x => x.IsGenericType)
                    .FirstOrDefault(x => x.GetGenericTypeDefinition() == typeof(IRequest<>));

            if (impementsIRequest != null)
            {
                yield return type;
                yield return impementsIRequest.GetGenericArguments()[0];
            }
        }
    }
}
